<template>
    <div class="page-container">
        <el-card class="box-card">
            <el-row justify="space-between">
                <el-col :span="20">
                    <el-form :inline="true" :model="search" class="demo-form-inline">
                        <el-form-item label="关键词：" label-width="180">
                            <el-input @input="bindSearch" v-model="search.keyword" style="width: 380px; height: 26px;"
                                clearable placeholder="输入词做匹对搜索，范围：文档名、分类、关联、创建人" />
                        </el-form-item>
                        <el-form-item label="创建时间：">
                            <el-date-picker v-model="dateList" type="daterange" size="small" start-placeholder="起始时间"
                                end-placeholder="结束时间" format="YYYY/MM/DD" value-format="x" @change="selectTimes" />
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <el-row justify="space-between">
                <div style="display: flex; flex-direction: row; font-weight: bold; color: gray;">
                    <div :style="search.type == 0 ? 'color: red' : ''" @click="selectTar(0)" style="cursor:pointer">全部</div>
                    <span style="margin: 0 10px;">|</span>
                    <div :style="search.type == 1 ? 'color: red' : ''" @click="selectTar(1)" style="cursor:pointer">我共享的文档</div>
                    <span style="margin: 0 10px;">|</span>
                    <div :style="search.type == 2 ? 'color: red' : ''" @click="selectTar(2)" style="cursor:pointer"> 我接收的文档</div>
                </div>
                <div style="display: flex; flex-direction: row; ">
                    <el-button size="small" icon="ele-Refresh" @click.stop.prevent="filterReset">加载列表</el-button>
                    <el-button :disabled="shareDocList.length == 0" size="small" icon="ele-Share"
                        @click="okShareUsers">批量共享</el-button>
                    <el-button size="small" icon="ele-Plus" @click="addMatter">上传知识库文件</el-button>
                    <el-button size="small" @click="openCreateFile">
                        <i class="fa fa-users" aria-hidden="true"></i>
                      新建共同编辑
                    </el-button>
                  <el-button size="small" icon="ele-FirstAidKit" @click="openMatterFile">新建事项文档</el-button>

                </div>
            </el-row>
            <div class="table-box">
                <el-table ref="multipleTableRef" :data="list" size="small" class="tableList"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="30" fixed="left" :selectable="selectable"></el-table-column>
                    <el-table-column v-for="item in header" :key="item.id" :prop="item.label"
                        :min-width="item.name.length > 5 ? `130px` : `90px`" align="center"
                        :width="item.label !== 'moduleVos' ? 'unset' : '400px'">
                        <template #header>
                            <span style="margin-right:2px;">{{ item.name }}</span>
                            <!-- 可搜索表头 -->
                            <el-popover placement="bottom" :width="100" trigger="click"
                                v-if="item.isFilter && item.filter == 'search'">
                                <template #reference>
                                    <el-icon :size="15" color="var(--el-color-primary)"><ele-Search /></el-icon>
                                </template>
                                <el-input :placeholder="`请输入${item.name}`" v-model.trim="search[item.label]" size="small"
                                    title="按下回车即可搜索" clearable @keydown.enter="bindSearch">
                                </el-input>
                            </el-popover>
                            <!-- 可筛选表头 -->
                            <el-popover placement="bottom" :width="60" trigger="click" @after-leave="bindSearch"
                                v-if="item.isFilter && item.filter == 'filter'">
                                <template #reference>
                                    <el-icon :size="15" color="var(--el-color-primary)"><ele-Filter /></el-icon>
                                </template>
                                <el-scrollbar max-height="600px">
                                    <el-radio-group v-model="search[item.label]" size="small"
                                        v-if="filterList[item.label].length > 0">
                                        <el-radio v-for="radio in filterList[item.label]" :key="radio.name"
                                            :label="radio.id" @click.prevent="onRadioChange(radio.id, item.label)">{{
                                                radio.name }}</el-radio>
                                    </el-radio-group>
                                    <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50"
                                        description="无数据" />
                                </el-scrollbar>
                            </el-popover>
                        </template>
                        <template #default="scope">
                            <template v-if="item.isFilter && item.filter == 'filter'">
                                {{ getStatusText(item.label, scope.row[item.label]) }}
                            </template>
                            <template v-else-if="item.label == 'moduleVos'">
                                <div v-for="(val, idx) in scope.row.moduleVos" style="margin-bottom: 5px;">
                                    <el-tag>{{ repliceStr(val.label) }}</el-tag>
                                </div>
                            </template>
                            <template v-else-if="item.label == 'uploadTime'">
                                {{ numParseTime(scope.row.uploadTime) }}
                            </template>
                            <template v-else-if="item.label == 'fileSize'">
                                {{ numFileSize(scope.row.fileSize) }}
                            </template>
                            <template v-else>{{ scope.row[item.label] }}</template>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" width="180px" label="操作">
                        <template #default="scope">
                            <el-button v-if="scope.row.userId == search.userId" size="small" link type="primary"
                                @click="shareDoc(scope.row)">共享</el-button>
                          <el-button size="small" link type="primary" @click="preview(scope.row)">预览</el-button>
                            <el-button v-if="scope.row.classId === 'cooperate'" size="small" link type="primary"
                                     @click="skipEdit(scope.row)">编辑</el-button>
<!--                            <el-button size="small" link type="primary" v-if="scope.row.userId === search.userId && scope.row.classId === 'cooperate'"-->
<!--                                       @click="openAuthority(scope.row)">权限设置</el-button>-->
                            <el-button size="small" link type="primary" @click="printDoc(scope.row)">下载</el-button>
                            <el-button size="small" link type="primary" @click="remove(scope.row)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="page-block">
                <el-pagination v-model:currentPage="search.current" v-model:page-size="search.size"
                    :page-sizes="[10, 20, 30, 40]" :small="true" :disabled="false" :background="false"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" :hide-on-single-page="false"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
        <el-dialog v-model="shareStatus" title="文档分享" width="30%" center>
            <div style="display: flex; flex-direction: row; align-items: center;">
                <span>选择分享的用户：</span>
                <el-select v-model="selectUsers" size="small" multiple placeholder="选择分享的用户" style="width: 240px">
                    <el-option v-for="item in shareUserList" :key="item.id" :label="item.nickname + '-' + item.phone"
                        :value="item.id" />
                </el-select>
            </div>
            <el-table :data="shareDocList" border size="small" style="width: 100%; margin-top: 20px;">
                <el-table-column prop="fileName" label="文档名称" />
                <el-table-column prop="fileType" label="文档类型" width="180">
                    <template #default="scope">
                        {{ filterList.fileType[scope.row.fileType - 1].name }}
                    </template>
                </el-table-column>
            </el-table>

          <p v-if="shareEdDocUsers.length === 0" style="font-size: 20px;margin-top: 10px">当前暂无共享人</p>

          <el-descriptions
              v-else
              :column="2"
              border
              size="small"
              style="margin-top: 10px"
          >
          <div v-for="item in shareEdDocUsers" :key="item.id">
            <el-descriptions-item label="用户名">
              {{item.nickname}}
            </el-descriptions-item>
            <el-descriptions-item label="联系方式">
              {{item.phone}}
            </el-descriptions-item>
          </div>
          </el-descriptions>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="shareReset">取消</el-button>
                    <el-button type="primary" @click="submitShare">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 选择事项类型 -->
        <el-dialog v-model="selectMatterStatus" title="选择事项" width="30%" center>
            <el-radio-group v-model="matterCode" >
                <el-radio :label="item.label" v-for="item in matterCodeList">{{ item.value}}</el-radio>
            </el-radio-group>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="selectMatterStatus = false">取消</el-button>
                    <el-button type="primary" @click="selectMatterType">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 事项组件 "-->
        <launch-matter v-model:visible="addMatterModel" v-model:relate-item="relateItem" v-model:detail-form="detailData" :module-code="goMatterCode" @closeCallback="closeCallback" />

        <!-- 选择创建协同文档类型 -->
        <el-dialog v-model="cooperateStatus" title="创建协同文档" width="600px" center>
          <div class="select">
            <div class="type-item" :class="{selectType:cooperateFile.fileType === 'word'}" @click="selectFileType('word')">
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#icon-word"></use>
              </svg>
              <p class="typeName">Word</p>
            </div>
            <div class="type-item" :class="{selectType:cooperateFile.fileType === 'cell'}" @click="selectFileType('cell')">
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#icon-excel"></use>
              </svg>
              <p class="typeName">Excel</p>
            </div>
            <div class="type-item" :class="{selectType:cooperateFile.fileType === 'slide'}" @click="selectFileType('slide')">
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#icon-powerpoint"></use>
              </svg>
              <p class="typeName">PPT</p>
            </div>
          </div>
          <div class="upload">
            <el-upload
                       ref="cooperateUpload"
                       drag
                       :multiple="false"
                       :auto-upload="false"
                       :headers="headers"
                       :limit="1"
                       :on-exceed="handleExceed"
                       @change="changeFile">
              <el-icon style="font-size: 30px">
                <ele-UploadFilled/>
              </el-icon>
              <div class="el-upload__text">
                拖拽上传或 <em>点击上传</em>
                <el-tooltip effect="light" content="不上传文件时,协同文档默认为空" placement="top-start">
                  <el-icon style="font-size:18px;position: relative;top:4px;left:6px"><ele-QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-upload>
          </div>
          <div class="association">
            <span><span style="color:red;display: inline;">*</span>关联：</span>
            <module-relate :relate-items="relateItems" v-model:selected="selected"/>
          </div>
          <div class="input-fileName">
            <span><span style="color:red;display: inline;">*</span>文件名称：</span>
            <el-input size="small" v-model="cooperateFile.fileName" style="width: 300px;" clearable placeholder="请输入文件名称"/>
          </div>

          <template #footer>
                  <span class="dialog-footer">
                      <el-button size="small" @click="cooperateStatus = false">取消</el-button>
                      <el-button size="small" type="primary" @click="createCooperateFile">确定</el-button>
                  </span>
          </template>
        </el-dialog>

        <cooperate-authority v-model:dialog-drawer="cooperateVisible" :file-log-id="currentFileLogId"/>

        <online-preview v-model:dialog-drawer="onlinePreviewisible" :file-data="currentFileData" />


    </div>
</template>

<script>
import { reactive, toRefs, onMounted, computed, ref, watch } from 'vue'
import { getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { Session } from '/@/utils/storage'
import Cookies from 'js-cookie'
import { genFileId } from 'element-plus'
import { parseTime } from '/@/utils/formatTime'
import { convertToFileSize, getDocumentType } from '/@/utils/common'
import ModuleRelate from '/@/views/matter/components/ModuleRelate.vue'
import {getRelatableId} from '/@/api/matter'
import api from '/@/api/commonApi'
import {createFile} from "../../../api/sys/cooperate";
import {getRelateItems} from '/@/api/matter'
import CooperateAuthority from "../components/CooperateAuthorityV2.vue";
import OnlinePreview from "../components/OnlinePreview.vue";
import { cooperateStates } from '/@/stores/space/cooperate'
import {useRouter} from 'vue-router'
import {checkVal} from "../../../utils/common";
import {useUserInfo} from '/@/stores/userInfo'
import '/@/theme/js/iconfont';

export default {
    name: 'Documents',
    components: {
        ModuleRelate,
        CooperateAuthority,
        OnlinePreview
    },
    props: {
        userId: { // 用户id
            type: String,
            default: null
        }
    },

    setup(props, context) {
        const { userId } = toRefs(props)
        const storesUserInfo = useUserInfo()
        const router = useRouter()
        const storesCooperate = cooperateStates()
        const instance = getCurrentInstance();
        const multipleTableRef = ref(null);
        const multipleSelection = ref([]);
        const cooperateUpload = ref()
        let relateItems = ref([])
        const userInfo = computed({
            get: () => userId.value,
            set: val => {
                state.search.userId = userId.value
            }
        })
        watch(() => userId.value,
            val => {
                state.search.userId = userId.value ? userId.value : Cookies.get('userId')
            }
        )
        watch(relateItems, (newValue) => {
          if(newValue.length === 0 ){
            //为空时处理...
          } else{
            state.fileModuleVo.modalList = []
            newValue.forEach(item =>{
              let labelTemp = item.label.split("/")
              console.log(labelTemp)
              let currentMatter = getMatterObject(labelTemp[0])
              state.modalListVo = {
                code:currentMatter.code, // 关联项code（文件列表使用）
                agendaMatterRelatableId:currentMatter.id, // 事项的可关联项
                agendaMatterRelatableName:currentMatter.label, // 事项的可关联项名称
                seRelateDataId:item.seRelateDataId, // 二级数据的id（客户、订单、项目、员工、候选人表）
                seRelateDataName:labelTemp[1], // 二级数据的名称
                thRelateDataId:item.thRelateDataId,// 三级数据id（暂时只有选客户后的订单id）
                thRelateDataName:item.thRelateDataId, // 三级数据的名称
                label:item.label,// 三个层级数据标签的拼接，客（客01（订01）） 或 客/客01/订01
              }
              state.fileModuleVo.modalList.push(state.modalListVo)
            })
          }
        },
       {deep: true}
    );
        const state = reactive({
            cooperateVisible:false,
            onlinePreviewisible:false,
            currentFileLogId:'',
            currentFileData:null,
            file:null,
            currentIsCooperate:0, //是否为协同文档 0->否  1->是
            uploadUrl: '/api/file/filaAttach/upload', // 上传地址
            headers: {
                '17work': Session.get('token')
            },
            // 表头数据
            header: [
                {
                    name: '文档名称',
                    isFilter: false,
                    filter: 'search',
                    label: 'oldFileName'
                },
                {
                    name: '分类',
                    isFilter: true,
                    filter: 'filter',
                    label: 'fileGroup'
                },
                {
                    name: '关联',
                    isFilter: false,
                    filter: 'search',
                    label: 'moduleVos'
                },
                {
                    name: '文档类型',
                    isFilter: true,
                    filter: 'filter',
                    label: 'fileType'
                },
                {
                    name: '创建时间',
                    isFilter: false,
                    filter: 'search',
                    label: 'uploadTime'
                },
                {
                    name: '创建人',
                    isFilter: false,
                    filter: 'filter',
                    label: 'userName'
                },
                {
                    name: '文档大小',
                    isFilter: false,
                    filter: 'search',
                    label: 'fileSize'
                }
            ],
            list: [],
            total: 0,
            dateList: [],
            shareStatus: false,
            cooperateStatus:false,
            shareUserList: [],
            selectUsers: [],
            shareDocList: [],
            shareDocIds: [],
            shareEdDocUsers:[],
            search: {
                current: 1,
                size: 10,
                keyword: '', // 关键词
                userId: '', // 当前用户
                type: 0, // 0 -> 全部， 1 -> 我的文件， 2 -> 接收的文件
                fileGroup: null, // 事项分类
                fileType: null, //文档分类
                startTime: null, // 开始时间
                endTime: null, // 结束时间
            },
            cooperateFile:{
              fileType:'word',
              fileName:'',
            },
            resultList:[],
            filterList: {
                fileGroup: [],
                fileType: [
                    { id: 1, name: 'JPG' },
                    { id: 2, name: 'PNG' },
                    { id: 3, name: 'GIF' },
                    { id: 4, name: 'XLS' },
                    { id: 5, name: 'DOC' },
                    { id: 6, name: 'PDF' },
                    { id: 7, name: 'PPT' },
                    { id: 8, name: 'TXT' },
                    { id: 9, name: 'HTML' },
                    { id: 10, name: 'SVG' },
                    { id: 11, name: 'DTD' },
                    { id: 12, name: 'MP3' },
                    { id: 13, name: 'MP4' },
                    { id: 14, name: '其他'},
                ],
                date: [
                  { id: 1, name: '创建时间' },
                  { id: 2, name: '修改时间' },
                ],
            },
            selectMatterStatus: false, // 选择事项类型
            matterCodeList: [],
            matterCode: 'EVENT',
            goMatterCode: '',
            addMatterModel: false, // 事项开关
            detailData: {},
            relateItem: {// 关联项
                agendaMatterRelatableId: null,
                seRelateDataId: null,
                label: null
            },
            moduleList:[],
            selected:{}, //测试用数据
            modalListVo:{
              code:null, // 关联项code（文件列表使用）
              agendaMatterRelatableId:null, // 事项的可关联项
              agendaMatterRelatableName:null, // 事项的可关联项名称
              seRelateDataId:null, // 二级数据的id（客户、订单、项目、员工、候选人表）
              seRelateDataName:null, // 二级数据的名称
              thRelateDataId:null,// 三级数据id（暂时只有选客户后的订单id）
              thRelateDataName:null, // 三级数据的名称
              label:null,// 三个层级数据标签的拼接，客（客01（订01）） 或 客/客01/订01
            },
            fileModuleVo:{
              fileLogId:null,
              code:null,
              fileGroup:null,
              classId:null,
              matterId:null,
              matterName:null,
              relevanceId:null,
              relevanceName:null,
              sourceType:null,
              src:null,
              modalList:[]
            },
        })
        // 获取对应事项的obj数据
        const getMatterObject = (name) => {
          for (let i = 0; i < state.moduleList.length; i++) {
            if(state.moduleList[i].label == name){
              return state.moduleList[i];
            }
          }
        }
        // 过滤
        const getStatusText = computed(() => {
            return (label, val) => {
                const result = state.filterList[label].find(item => {
                    return item.id == String(val)
                })
                return result ? result.name : ''
            }
        })
        // 切换单选框
        const onRadioChange = (val, type) => {
            if (state.search[type] == String(val)) {
                state.search[type] = ''
                return
            }
            state.search[type] = val
        }
        // 初始化列表
        const getList = () => {
            api.esDocumentList(state.search).then(res => {
                state.list = res.data.hotels
                state.total = res.data.total
            })
        }
        // 共享
        const shareDoc = (val) => {
          if(val.userId === state.search.userId && val.classId === 'cooperate'){
            openAuthority(val)
          }else{
            var ultipleTabInstance = toRefs(instance.refs.multipleTableRef)
            ultipleTabInstance.clearSelection.value()
            state.selectUsers = []
            state.shareDocList = [val]
            state.shareDocIds = [val.id]
            state.currentIsCooperate = val.classId === 'cooperate' ? 1 : 0
            okShareUsers(val)
          }
        }
        // 打开共享弹窗
        const okShareUsers = (val) => {
            api.shareDocUsers({ ids: state.shareDocIds + '' }).then(res => {
                if (val != null){
                  api.shareEdDocUsers(val.id).then(userList =>{
                    for (let i = 0; i < userList.data.length; i++) {
                      if(storesUserInfo.userInfos.id === userList.data[i].id){
                        userList.data.splice(i,1);
                      }
                    }
                    state.shareEdDocUsers = userList.data
                  })
                }else{
                  state.shareEdDocUsers = []
                }
                state.shareUserList = res.data
                state.shareStatus = true
            })
        }
        // 下载
        const printDoc = (val) => {
            ElMessageBox.confirm(
                '下载文件：' + val.oldFileName,
                '文件下载',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true,
                }
            ).then(() => {
                api.uploadFile({
                    fileUrl: val.fileVisitSite,
                    oldName: val.oldFileName
                }).then(response => {
                    const blob = new Blob([response.data], { type: 'application/blob' })
                    const reader = new FileReader()
                    reader.readAsDataURL(blob)
                    reader.onload = e => {
                        const a = document.createElement('a')
                        a.download = decodeURIComponent(val.oldFileName)
                        if (typeof e.target.result === 'string') {
                            a.href = e.target.result
                        }
                        a.click()
                    }

                })
            })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消下载',
                    })
                })
        }
        // 移除
        const remove = (val) => {
            ElMessageBox.confirm(
                '移除文档：' + val.oldFileName,
                '移除',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error',
                    center: true,
                }
            ).then(() => {
                api.removeDoc(val.id).then(res => {
                    setTimeout(() => {
                        ElMessage({
                            type: 'success',
                            message: '移除成功',
                        })
                        getList()
                    }, 1000);
                })
            })
        }
        // 条数修改
        const handleSizeChange = e => {
            state.search.size = e
            getList()
        }
        // 页码修改
        const handleCurrentChange = e => {
            state.search.current = e
            getList()
        }
        // 搜索
        const bindSearch = () => {
            state.search.current = 1
            getList()
        }
        // 重置
        const filterReset = () => {
            state.dateList = []
            state.search = {
                current: 1,
                size: 20,
                keyword: '', // 关键词
                userId: userId.value ? userId.value : Cookies.get('userId'), // 当前用户
                type: 0, // 0 -> 全部， 1 -> 我的文件， 2 -> 接收的文件
                fileGroup: null, // 事项分类
                fileType: null, //文档分类
                startTime: null, // 开始时间
                endTime: null, // 结束时间
            }
            getList()
        }
        //打开创建协同文档
        const openCreateFile = () => {
          state.cooperateFile.fileName = ''
          relateItems.value = []
          state.cooperateStatus = true;
        }
        // 字符串替换
        const repliceStr = val => {
            let str = val.replace("/", "：")
            return str.replace(/\//g, "-")
        }
        // 事项类型
        const getMatterType = () => {
            api.getMatterCodes().then(res => {
                let list = []
                res.data.forEach((item, index) => {
                    list.push({ id: item.value, name: item.value })
                })

                //加入协同文档前端的显示和筛选,但是后台是没有这个的
                list.push({ id:"协同文档", name: "协同文档" })

                state.filterList.fileGroup = list
            })
        }
        // 时间搓转换
        const numParseTime = (val) => {
            return parseTime(val, "{y}-{m}-{d} {h}:{i}:{s}")
        }
        // 文件大小转换
        const numFileSize = (val) => {
            return convertToFileSize(val)
        }
        // 切换类型
        const selectTar = (val) => {
            state.search.type = val
            getList()
        }
        // 多选
        const handleSelectionChange = (val, item) => {
            state.selectUsers = []
            state.shareDocIds = []
            state.shareDocList = []
            val.forEach(element => {
                if (element.userId == state.search.userId) {
                    state.shareDocList.push(element)
                    state.shareDocIds.push(element.id)
                }
            });
        }
        // 分享框重置
        const shareReset = () => {
            state.shareUserList = []
            state.selectUsers = []
            state.shareDocIds = []
            var ultipleTabInstance = toRefs(instance.refs.multipleTableRef)
            ultipleTabInstance.clearSelection.value()
            state.shareStatus = false
        }
        // 确定共享
        const submitShare = () => {
            api.addShareDoc({
                users: state.selectUsers,
                docIds: state.shareDocIds,
                isCooperate: state.currentIsCooperate
            }).then(res => {
                ElMessage.success("分享成功")
                shareReset()
                getList()
            })
        }
        // 禁选
        const selectable = (row) => {
            return row.userId == state.search.userId ? row.classId === 'cooperate' ? false : true : false
        }
        // 筛选时间
        const selectTimes = (val) => {
            if(val && val.length > 0) {
                state.search.startTime = val[0]
                state.search.endTime = (val[1] + 86399999)
            }else{
                state.search.startTime = null
                state.search.endTime = null
            }
            getList()
        }
        // 添加事项
        const addMatter = () => {
            state.selectMatterStatus = true
        }
        // 加载事项列表、统计、线索数量
        const closeCallback = () => {
            state.addMatterModel = false
            getList()
        }
        // 获取事项模块类型
        const getModuleCode = () => {
            api.moduleCodes().then(res => {
                state.matterCodeList = res.data
            })
        }
        // 选择事项类型
        const selectMatterType = () => {
            getRelatableId(state.matterCode).then(res => {
                state.relateItem.agendaMatterRelatableId = res.data.id
                state.relateItem.label = '文档/'
                state.goMatterCode = state.matterCode
                //state.goMatterCode = res.data.moduleCode //这个因为全大写,枚举类会报错
                state.addMatterModel = true
            }).catch(e => console.log(e))
        }
        //选择创建文档类型
        const selectFileType = (val) => {
          state.cooperateFile.fileType = val
        }
        //进入协同文档
        const skipEdit = (row) => {
          storesCooperate.owner = row.userName
          storesCooperate.title = row.oldFileName
          storesCooperate.fileLogId = row.id
          storesCooperate.fileVisitSite = row.fileVisitSite
          storesCooperate.uploadTime = numParseTime(row.uploadTime)
          storesCooperate.compileFileName = row.compileFileName
          router.push({name:"SpaceCollaborative"})
        }
        //提交创建文档
        const createCooperateFile = () => {
          if(state.fileModuleVo.modalList.length === 0){
            ElMessage.error("请选择关联")
            return;
          }
          if(state.cooperateFile.fileName === null || state.cooperateFile.fileName === ''){
            ElMessage.error("文件名称不能为空")
            return;
          }
          if(!checkVal(state.cooperateFile.fileName)){
            ElMessage.error("文件名称不能包含特殊字符")
            return;
          }
          createFile({type:state.cooperateFile.fileType,fileName:state.cooperateFile.fileName,file:state.file}).then(res =>{
            state.fileModuleVo.fileLogId = res.data.fileLogId
            state.fileModuleVo.sourceType = 1
            api.cooperateFileRelevanceModule(state.fileModuleVo).then(res =>{
              if(res.data){
                ElMessage.success("创建成功!")
                state.cooperateStatus = false;
                //延迟加载 不然es可能还没加进去
                setTimeout(function () {
                  getList()
                },1000);
              }
            })
          })
        }
        //打开权限设置
        const openAuthority = (row) => {
          state.currentFileLogId = row.id
          state.cooperateVisible = true
        }
        //修改文件
        const changeFile = (file) => {
          const array = file.name.split(".")
          const suffix = getDocumentType(array[1])
          if(suffix == null){
            ElMessage.error("请上传Office文件")
            cooperateUpload.value.clearFiles()
            return;
          }
          state.file = file.raw
          state.cooperateFile.fileName = array[0]
          state.cooperateFile.fileType = suffix
        }
        //替换上一个文件
        const handleExceed = (files) => {
          cooperateUpload.value.clearFiles()
          const file = files[0]
          file.uid = genFileId()
          cooperateUpload.value.handleStart(file)
        }
        //在线预览
        const preview = (row) => {
          state.currentFileData = row
          state.onlinePreviewisible = true
        }
        //新建事项文档
        const openMatterFile = () => {

        }
        onMounted(() => {
            state.search.userId = userId.value ? userId.value : Cookies.get('userId')
            getModuleCode()
            getMatterType()
            getRelateItems().then(res =>{
              state.moduleList = res.data
            })
            getList()
        })
        return {
            ...toRefs(state),
            ModuleRelate,
            CooperateAuthority,
            OnlinePreview,
            getStatusText,
            relateItems,
            storesCooperate,
            router,
            cooperateUpload,
            getList,
            remove,
            selectTar,
            selectable,
            printDoc,
            shareDoc,
            addMatter,
            closeCallback,
            shareReset,
            submitShare,
            okShareUsers,
            filterReset,
            bindSearch,
            repliceStr,
            selectTimes,
            numFileSize,
            numParseTime,
            onRadioChange,
            selectMatterType,
            handleSizeChange,
            handleCurrentChange,
            handleSelectionChange,
            createCooperateFile,
            selectFileType,
            openCreateFile,
            getMatterObject,
            openAuthority,
            skipEdit,
            changeFile,
            handleExceed,
            preview,
            openMatterFile
        }
    }
}

</script>

<style lang="scss" scoped>
.page-container {
    padding: 5px 15px 15px !important;

    .table-box {
        background: #fff;
        margin-top: 10px;

        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }

        .tableList {
            border: 1px solid var(--el-table-border-color);
            border-bottom: none;

            :deep(thead .cell) {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            :deep(thead th:last-child .cell) {
                justify-content: center;
            }

            :deep(thead .el-icon) {
                margin-top: -2px;
                cursor: pointer;
            }

            .primary {
                cursor: pointer;
                color: var(--el-color-primary);
            }

            :deep(.el-button) {
                margin-left: 0;
                margin-right: 12px;
            }

            :deep(.el-table__body td.el-table__cell) {
                border-right: 1px solid var(--el-border-color-light);
                padding: 0;

                &:last-child {
                    border-right: none;
                }
            }

            .order-row-item {
                width: 100%;

                :deep(.el-col) {
                    border-right: 1px solid var(--el-border-color-light);
                    text-align: center;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    &:last-child {
                        border-right: none;
                    }

                    &:first-child,
                    &:nth-child(2) {
                        text-align: left;
                        justify-content: flex-start;
                        padding-left: 8px;
                    }
                }
            }

            .order-border-none {
                :deep(.el-col) {
                    border: none;
                }
            }
        }
    }

  .select{
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
    .type-item{
      cursor: pointer;
      padding: 20px 35px 20px 35px;
      border-radius: 15px;
      margin: 2px;
      .iconfont{
        font-size: 50px;
      }
    }

    .type-item:hover{
      background-color: #e7e7e7;
    }

    .selectType{
      border: 2px solid #676767;
      background-color: #e7e7e7;
    }

    .typeName{
      text-align: center;
      margin-top: 10px;
    }
  }

  .input-fileName{
    display: flex;
    padding: 10px;
    span{
      width: 80px;
      text-align: right;
    }
  }

  .association{
    display: flex;
    padding: 10px;
    span{
      width: 80px;
      text-align: right;
    }
  }

  .iconfont {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
}
</style>
